package goulu.bloggy.com.Connections;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import goulu.bloggy.com.Helpers.PostHelper;
import goulu.bloggy.com.Models.Post;
import goulu.bloggy.com.Models.User;

public class PostMysqlConnection implements Runnable
{
	private Handler responseHandler;
	public static final int ADD_POST = 1;
	public static final int GET_POST = 2;
	public static final int UPDATE_POST = 3;
	public static final int GET_PUBLISHED_POSTS = 4;
	public static final int DELETE_POST = 5;
	public static final int ERROR = 0;
	
	private int connectionMethod;
	private Post handledPost;
	private int handledUserId;
	private String handledUsername;
	
	public PostMysqlConnection(Handler responseHandler, int connectionMethod, Post handledPost)
	{
		this.responseHandler = responseHandler;
		this.connectionMethod = connectionMethod;
		this.handledPost = handledPost;
	}
	
	public PostMysqlConnection(Handler responseHandler, int connectionMethod, int UserId)
	{
		this.responseHandler = responseHandler;
		this.connectionMethod = connectionMethod;
		this.handledUserId = UserId;
	}
	
	public PostMysqlConnection(Handler responseHandler, int connectionMethod, String Username)
	{
		this.responseHandler = responseHandler;
		this.connectionMethod = connectionMethod;
		this.handledUsername = Username;
	}
	
	public void getPostsByUserId(int id)
	{
		ArrayList<Post> posts = new ArrayList<Post>();
		try
		{		
			ArrayList<NameValuePair> postEntity = new ArrayList<NameValuePair>();
			postEntity.add(new BasicNameValuePair("id", String.valueOf(id)));
			HttpClient client = new DefaultHttpClient();
			HttpPost post = new HttpPost("http://users.metropolia.fi/~peteraa/android/bloggy/getPosts.php");
			post.setEntity(new UrlEncodedFormEntity(postEntity));
			HttpResponse response = client.execute(post);
			HttpEntity entity = response.getEntity();
			String result = EntityUtils.toString(entity);	
			Log.d("query result: ", result);
			try
			{
				JSONArray jsonArray = new JSONArray(result);
				for(int i = 0; i < jsonArray.length(); i++)
				{
					Post blogpost = new Post();
					JSONObject jObject = jsonArray.getJSONObject(i);
					blogpost.setId(jObject.getInt("id"));
					blogpost.setUserid(jObject.getInt("userid"));
					blogpost.setTitle(jObject.getString("title"));
					blogpost.setContent(jObject.getString("content"));
					blogpost.setMood(jObject.getString("mood"));
					blogpost.setCreationDate(PostHelper.stringToGregorianCalendar(jObject.getString("creationdate")));
					blogpost.setPublished(PostHelper.intToBoolean(jObject.getInt("published")));
					posts.add(blogpost);
				}
				Message msg = responseHandler.obtainMessage();
				msg.obj =  posts;
				msg.what = GET_POST;
				responseHandler.sendMessage(msg);
			}
			catch(Exception e)
			{
				Message msg = responseHandler.obtainMessage();
				if(result.equals("null"))
				{
					msg.obj = "No blogposts in db!";
				}
				else
				{
					msg.obj = "Connection failed!";
				}
				msg.what = ERROR;
				responseHandler.sendMessage(msg);
				e.printStackTrace();
			}
		}
		catch(Exception e)
		{
			Message msg = responseHandler.obtainMessage();
			e.printStackTrace();
			msg.obj = "Connection failed!";
			msg.what = ERROR;
			responseHandler.sendMessage(msg);
		}
	}
	
	public void getPublishedPostsByUsername(String username)
	{
		ArrayList<Post> posts = new ArrayList<Post>();
		try
		{		
			Log.d("searched username is = " , username);
			ArrayList<NameValuePair> postEntity = new ArrayList<NameValuePair>();
			postEntity.add(new BasicNameValuePair("username", username));
			HttpClient client = new DefaultHttpClient();
			HttpPost post = new HttpPost("http://users.metropolia.fi/~peteraa/android/bloggy/getPublishedPosts.php");
			post.setEntity(new UrlEncodedFormEntity(postEntity));
			HttpResponse response = client.execute(post);
			HttpEntity entity = response.getEntity();
			String result = EntityUtils.toString(entity);	
			Log.d("query result: ", result);
			try
			{
				JSONArray jsonArray = new JSONArray(result);
				for(int i = 0; i < jsonArray.length(); i++)
				{
					Post blogpost = new Post();
					JSONObject jObject = jsonArray.getJSONObject(i);
					blogpost.setId(jObject.getInt("id"));
					blogpost.setUserid(jObject.getInt("userid"));
					blogpost.setTitle(jObject.getString("title"));
					blogpost.setContent(jObject.getString("content"));
					blogpost.setMood(jObject.getString("mood"));
					blogpost.setCreationDate(PostHelper.stringToGregorianCalendar(jObject.getString("creationdate")));
					blogpost.setPublished(PostHelper.intToBoolean(jObject.getInt("published")));
					posts.add(blogpost);
				}
				Message msg = responseHandler.obtainMessage();
				msg.obj =  posts;
				msg.what = GET_PUBLISHED_POSTS;
				responseHandler.sendMessage(msg);
			}
			catch(Exception e)
			{
				Message msg = responseHandler.obtainMessage();
				if(result.equals("null"))
				{
					msg.obj = "No blogposts in db!";
				}
				else
				{
					msg.obj = "Could not find username " + username;
				}
				msg.what = ERROR;
				responseHandler.sendMessage(msg);
				e.printStackTrace();
			}
		}
		catch(Exception e)
		{
			Message msg = responseHandler.obtainMessage();
			e.printStackTrace();
			msg.obj = "Connection failed!";
			msg.what = ERROR;
			responseHandler.sendMessage(msg);
		}
	}
	
	public void insertPost(Post blogpost)
	{
		GregorianCalendar cal = (GregorianCalendar)Calendar.getInstance();
		String currentDate = PostHelper.gregorianCalendarToString(cal);
		
		ArrayList<NameValuePair> postEntity = new ArrayList<NameValuePair>();
		postEntity.add(new BasicNameValuePair("userid", String.valueOf(blogpost.getUserid())));
		postEntity.add(new BasicNameValuePair("title", blogpost.getTitle()));
		postEntity.add(new BasicNameValuePair("content", blogpost.getContent()));
		postEntity.add(new BasicNameValuePair("mood", blogpost.getMood()));
		postEntity.add(new BasicNameValuePair("creationdate", currentDate));
		postEntity.add(new BasicNameValuePair("published", String.valueOf(PostHelper.booleanToInt(blogpost.isPublished()))));
		try
		{
			HttpClient client = new DefaultHttpClient();
			HttpPost post = new HttpPost("http://users.metropolia.fi/~peteraa/android/bloggy/addPost.php");
			post.setEntity(new UrlEncodedFormEntity(postEntity));
			client.execute(post);
			Message msg = responseHandler.obtainMessage();
			msg.what = ADD_POST;
			msg.obj = "Blogpost submitted!";
			responseHandler.sendMessage(msg);
		}
		catch(Exception e)
		{
			Log.e("PostMysqlConnection.insertPost()", "httppost failed", e);
		}
	}
	
	public void updatePost(Post blogpost)
	{
		ArrayList<NameValuePair> postEntity = new ArrayList<NameValuePair>();
		postEntity.add(new BasicNameValuePair("id", String.valueOf(blogpost.getId())));
		postEntity.add(new BasicNameValuePair("title", blogpost.getTitle()));
		postEntity.add(new BasicNameValuePair("content", blogpost.getContent()));
		postEntity.add(new BasicNameValuePair("mood", blogpost.getMood()));
		postEntity.add(new BasicNameValuePair("published", String.valueOf(PostHelper.booleanToInt(blogpost.isPublished()))));
		try
		{
			HttpClient client = new DefaultHttpClient();
			HttpPost post = new HttpPost("http://users.metropolia.fi/~peteraa/android/bloggy/updatePost.php");
			post.setEntity(new UrlEncodedFormEntity(postEntity));
			client.execute(post);
			Message msg = responseHandler.obtainMessage();
			msg.what = UPDATE_POST;
			msg.obj = "Blogpost successfully edited!";
			responseHandler.sendMessage(msg);
		}
		catch(Exception e)
		{
			Log.e("PostMysqlConnection.updatePost()", "httppost failed", e);
		}
	}

	@Override
	public void run() 
	{
		if(connectionMethod == ADD_POST)
		{
			this.insertPost(handledPost);
		}
		else if(connectionMethod == GET_POST)
		{
			this.getPostsByUserId(handledUserId);
		}
		else if(connectionMethod == UPDATE_POST)
		{
			this.updatePost(handledPost);
		}
		else if(connectionMethod == GET_PUBLISHED_POSTS)
		{
			this.getPublishedPostsByUsername(handledUsername);
		}
		else if(connectionMethod == DELETE_POST)
		{
			this.deletePost(handledPost);
		}
		
	}

	private void deletePost(Post blogpost) 
	{
		ArrayList<NameValuePair> postEntity = new ArrayList<NameValuePair>();
		postEntity.add(new BasicNameValuePair("id", String.valueOf(blogpost.getId())));

		try
		{
			HttpClient client = new DefaultHttpClient();
			HttpPost post = new HttpPost("http://users.metropolia.fi/~peteraa/android/bloggy/deletePost.php");
			post.setEntity(new UrlEncodedFormEntity(postEntity));
			client.execute(post);
			Message msg = responseHandler.obtainMessage();
			msg.what = DELETE_POST;
			msg.obj = "Blogpost deleted!";
			responseHandler.sendMessage(msg);
		}
		catch(Exception e)
		{
			Log.e("PostMysqlConnection.deletePost()", "httppost failed", e);
		}	
	}
}
